<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="excelUploaderVisible" center title="数据导入" top="25vh"
             width="30%">
    <el-upload
        ref="upload"
        :auto-upload="false"
        :on-error="handleError"
        :on-success="handleSuccess"
        accept=".xlsx"
        action="/api/upload"
        class="upload-demo"
        drag
        limit="1"
        multiple
        style="text-align: center">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传xlsx文件，
        <el-button type="text" @click="getTemplate" style="font-size: 12px">下载模板</el-button>
      </div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-row :gutter="20">
        <el-col :offset="6" :span="18">
          <el-button size="mini" @click="excelUploaderVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="commit">确 定</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      excelUploaderVisible: false
    }
  },
  methods: {
    showExcelUploader() {
      this.excelUploaderVisible = true;
    },
    commit() {
      this.$refs.upload.submit();
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.$message.success("导入成功");
        this.$refs.upload.clearFiles();
        this.excelUploaderVisible = false;
        this.$emit("success-upload");
      } else {
        this.$message.error("导入失败，" + file.name + res.description);
      }
    },
    handleError(err, file, fileList) {
      this.$message.error("导入失败");
    },
    getTemplate() {
      this.$axios.get("/api/template", {
        responseType: "blob",
      }).then(res => {
        let url = window.URL.createObjectURL(new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', 'student.xlsx')
        document.body.appendChild(link)
        link.click()
        link.remove()
      }).catch((e) => {
        console.log(e)
      })
    }
  },
  mounted() {
    document.body.appendChild(this.$el);
  },
  beforeDestroy() {
  },
  destroyed() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload-dragger {
  width: 20vw;
}
</style>